# -*- coding = utf-8 -*-
# @Time : 2022/3/11 9:37
# @Author :Henry L
# @File : nash.py
# @Software : PyCharm
import csv
import json
import os
import random
import time
import execjs
import requests
import logging



logging.basicConfig(level=logging.DEBUG,filename='xiangmu.log',format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') #设置日志级别
"""注意这里我改了execjs中文件的编码格式"""
regn_code_url = "https://fuwu.nhsa.gov.cn/ebus/fuwu/api/nthl/api/dic/queryAdmdvsTree"
lv_and_type_url = "https://fuwu.nhsa.gov.cn/ebus/fuwu/api/nthl/api/fixed/queryDicByType"
# result_url = "https://fuwu.nhsa.gov.cn/ebus/fuwu/api/nthl/api/fixed/queryFixedHospital"
result_url = "https://fuwu.nhsa.gov.cn/ebus/fuwu/api/nthl/api/CommQuery/queryWmTcmpatInfoBFromEs"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36"

with open('nash.js', 'r', encoding='utf-8') as f:
    nhsa_js = execjs.compile(f.read())


def get_headers():
    """获取 header 参数，每次请求改变"""
    headers = nhsa_js.call("getHeaders")
    headers["User-Agent"] = UA
    headers["Content-Type"] = "application/json"
    headers["Host"] = "fuwu.nhsa.gov.cn"
    headers["Origin"] = "https://fuwu.nhsa.gov.cn"
    headers["Referer"] = "https://fuwu.nhsa.gov.cn/nationalHallSt/"
    # print(headers)
    return headers


def get_regn_code():
    """获取城市代码，返回结果无加密"""
    payload = {"data": {"transferFlag": ""}}
    response = requests.post(url=regn_code_url, json=payload, headers=get_headers())
    region_dic = json.loads(response.text)
    # print(region_dic)
    sale_num = region_dic.get("data")
    # print(sale_num)
    # sale_num1 = sale_num.get("code")
    for i in sale_num:
        a = i['code']
        c = i['name']
        b = i['list']
        csvFile = open('yaodian.csv', 'a', encoding='utf-8', newline='')
        writer = csv.writer(csvFile)
        writer.writerow([a, c])
        for n in b:
            # print(n)
            # for n in m:
            a = n['code']
            c = n['name']
            # print(a)
            csvFile = open('yaodian.csv', 'a', encoding='utf-8', newline='')
            writer = csv.writer(csvFile)
            writer.writerow([a, c])
        # print(a)
        # print(b)
    # sale_num = region_dic.get("data")
    # csvFile = open('yaodian.csv', 'a', encoding='utf-8', newline='')
    # writer = csv.writer(csvFile)
    # writer.writerow([ip, port, anonymous, type, location, speed, date])
    return region_dic['data']



def get_medins_lv_or_type_code(key):
    """获取医疗机构等级 (LV) or 类型 (TYPE) 代码"""
    if key == "LV":
        payload = {"type": "MEDINSLV"}
    elif key == "TYPE":
        payload = {"type": "MEDINS_TYPE"}   
    else:
        print("输入有误!")
        return
    encrypted_payload = nhsa_js.call("getEncryptedData", payload)
    encrypted_data = requests.post(url=lv_and_type_url, json=encrypted_payload, headers=get_headers()).json()
    decrypted_data = nhsa_js.call("getDecryptedData", encrypted_data)
    return decrypted_data

def get_result(pagenum):
    requests.adapters.DEFAULT_RETRIES = 15
    s = requests.session()
    s.keep_alive = False

    payload = {
        'keyWords': '', 'drugType': '', 'pageNo': pagenum, 'pageSize': 100, 'medListCodg': 'X'
    }
    encrypted_payload = nhsa_js.call("getEncryptedData", payload)
    sleep_time = 0.1 * random.randint(1, 20)
    time.sleep(random.randint(10, 20) + sleep_time)
    encrypted_data = requests.post(url=result_url, json=encrypted_payload, headers=get_headers(), timeout=60).json()
    while encrypted_data['code'] != 0:
        time.sleep(random.randint(10, 20) + sleep_time)
        encrypted_data = requests.post(url=result_url, json=encrypted_payload, headers=get_headers(), timeout=60).json()
    decrypted_data = nhsa_js.call("getDecryptedData", encrypted_data)
    return decrypted_data


def to_csv(result, writer, province, city):
    for row in result:
        row["province"] = province
        if city != '':
            row["city"] = city
        writer.writerow(row)


def main():
    import csv

    # ... 其他代码 ...

    with open('data.csv', 'a+', encoding='utf-8', newline='') as file:
        header = [
            'drugstdcode', 'updtTime', 'drugType', 'rid', 'opterName', 'minPacCnt',
            'lstdLicHolder', 'smlVerName', 'crterName', 'verName', 'mktStas',
            'crterId', 'optinsNo', 'aprvnoEnddate', 'drugRegAppVletrElecacs',
            'consevalDrug', 'crteOptinsNo', 'drugDosform', 'crteTime',
            'prodentpName', 'aprvno', 'drugExpy', 'optTime', 'opterId',
            'manl', 'minPacunt', 'pacmatl', 'eachDos', 'drugProdname',
            'splmAppyAppvletrFile', 'medListCodg', 'drugSpec', 'regName',
            'efccAtd', 'subpckFcty', 'tramDataId', 'ver', 'minPrepunt',
            'isuFlag', 'efftTime', 'regDosform', 'lstdDruglistDrug',
            'convrat', 'minPrcunt', 'valiFlag', 'engName', 'chldMedc',
            'regSpec', 'prodentpCode', 'otcFlag'
        ]

        # 使用DictWriter
        writer = csv.DictWriter(file, fieldnames=header)
        # 写入表头
        writer.writeheader()

        # 获取城市代码
        with open("index.csv", "w+") as index:
            for i in range(0, 1399):
                time.sleep(random.randint(2, 10))
                index.write(f"{i}\n")  # 每个数字后添加换行符

                # 假设response.list是一个字典列表
                response = get_result(i)
                for data_dict in response['list']:
                    filtered_dict = {k: v for k, v in data_dict.items() if k in header}
                    writer.writerow(filtered_dict)  # 直接写入字典


if __name__ == "__main__":
    main()
    # dff = pd.read_csv('data1.csv')
    # engine = create_engine('postgresql://postgres:j3IA6rebQ9NG@192.168.6.226:5432/odp20210825')
    # '''index : bool, default True
    #             Write DataFrame index as a column. Uses `index_label` as the column
    #             name in the table.'''
    # dff.to_sql('yibao_accountbase_' + time.strftime('%Y%m%d', time.localtime(time.time())),
    #            engine, index=False, if_exists='replace')
